import { defineStore } from 'pinia'
import type { LoginLogDto, LoginLogPagedRequest } from '@/api/log'
import logApi from '@/api/log'
import type { PagedList } from '@/types/api'

interface LogState {
  loginLogs: PagedList<LoginLogDto>
  loading: boolean
  searchForm: LoginLogPagedRequest
}

export const useLogStore = defineStore('log', {
  state: (): LogState => ({
    loginLogs: {
      items: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      totalPages: 0
    },
    loading: false,
    searchForm: {
      pageIndex: 1,
      pageSize: 10,
      userName: '',
      status: undefined,
      startTime: undefined,
      endTime: undefined,
      orderBy: 'loginTime',
      isDesc: true
    }
  }),

  actions: {
    // 获取登录日志列表
    async getLoginLogs() {
      this.loading = true
      try {
        const response = await logApi.getLoginLogs(this.searchForm)
        if (response.data.isSuccess) {
          this.loginLogs = response.data.data
        }
      } finally {
        this.loading = false
      }
    },

    // 获取最近一周登录日志
    async getRecentLoginLogs() {
      this.loading = true
      try {
        const response = await logApi.getRecentLoginLogs()
        if (response.data.isSuccess) {
          this.loginLogs = response.data.data
        }
      } finally {
        this.loading = false
      }
    },

    // 按用户名搜索
    async searchByUserName(userName: string) {
      this.loading = true
      try {
        const response = await logApi.getUserLoginLogs(userName)
        if (response.data.isSuccess) {
          this.loginLogs = response.data.data
        }
      } finally {
        this.loading = false
      }
    },

    // 清理日志
    async cleanLogs(beforeTime: string) {
      const response = await logApi.cleanLoginLogs(beforeTime)
      if (response.data.isSuccess) {
        await this.getLoginLogs()
        return response.data.data
      }
      return 0
    },

    // 按天数清理日志
    async cleanLogsByDays(days: number) {
      const response = await logApi.cleanLoginLogsByDays(days)
      if (response.data.isSuccess) {
        await this.getLoginLogs()
        return response.data.data
      }
      return 0
    },

    // 重置搜索表单
    resetSearchForm() {
      this.searchForm = {
        pageIndex: 1,
        pageSize: 10,
        userName: '',
        status: undefined,
        startTime: undefined,
        endTime: undefined,
        orderBy: 'loginTime',
        isDesc: true
      }
    }
  }
})
